package br.com.musclebook.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.musclebook.entity.Exercise;
import br.com.musclebook.enums.ExerciseCategory;

class ExerciseDAO extends BaseDAO {

    public Exercise find(Long id) {
	EntityManager em = this.getEm();
	Query query = em.createNamedQuery("Exercise.findById");
	query.setParameter("id", id);
	return (Exercise) query.getSingleResult();
    }
    
    public Exercise insert(Exercise exercise) {
	EntityManager em = this.getEm();
	em.persist(exercise);
	return exercise;
    }
    
    public Exercise update(Exercise exercise) {
	EntityManager em = this.getEm();
	return em.merge(exercise);
    }
    
    @SuppressWarnings("unchecked")
    public List<Exercise> listByCategory(ExerciseCategory category, Long userId) {
	EntityManager em = this.getEm();
	
	List<Exercise> exercises = new ArrayList<Exercise>();
	
	Query query = em.createNamedQuery("BuildInExercise.listByCategory");
	query.setParameter("category", category);
	exercises.addAll(query.getResultList());
	
	query = em.createNamedQuery("UserExercise.listByCategory");
	query.setParameter("category", category);
	query.setParameter("userId", userId);
	
	exercises.addAll(query.getResultList());
	
	return exercises;
    }
    
    @SuppressWarnings("unchecked")
    public List<Exercise> listByName(String name, Long userId) {
	EntityManager em = this.getEm();
	
	List<Exercise> exercises = new ArrayList<Exercise>();
	
	Query query = em.createNamedQuery("BuildInExercise.listByName");
	query.setParameter("name", "%" + name.toUpperCase() + "%");
	exercises.addAll(query.getResultList());
	
	query = em.createNamedQuery("UserExercise.listByName");
	query.setParameter("name", "%" + name + "%");
	query.setParameter("userId", userId);
	
	exercises.addAll(query.getResultList());
	
	return exercises;
    }
    
    @SuppressWarnings("unchecked")
    public List<String> listNames(String name, Long userId) {
	EntityManager em = this.getEm();
	
	List<String> names = new ArrayList<String>();
	
	Query query = em.createNamedQuery("BuildInExercise.listNames");
	query.setParameter("name", "%" + name.toUpperCase() + "%");
	names.addAll(query.getResultList());
	
	query = em.createNamedQuery("UserExercise.listNames");
	query.setParameter("name", "%" + name + "%");
	query.setParameter("userId", userId);
	
	names.addAll(query.getResultList());
	
	return names;
    }
}
